package com.ruoyi.system.controller;

import com.google.code.kaptcha.Producer;
import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.core.constant.Constants;

import com.ruoyi.common.core.utils.uuid.IdUtils;
import com.ruoyi.common.redis.service.RedisService;

import com.ruoyi.system.DTO.Reques.user.LoginUserDTO;
import com.ruoyi.system.pojo.vo.UserVO;
import com.ruoyi.system.service.UserService;
import com.ruoyi.system.utils.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user-service/user")
public class UserController {

    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedisService redisService;

    @Autowired
    private UserService userService;

    /**
     * 生成验证码
     */
    @GetMapping("/imageCode/{imageCode}")
    public void imageCode(@PathVariable("imageCode") String imageCode, HttpServletResponse response) throws IOException {

        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
        String code;
        BufferedImage image;
        if ("math".equalsIgnoreCase(imageCode)) {
            String capText = captchaProducerMath.createText();
            code = capText.substring(capText.lastIndexOf("@")  + 1);
            image = captchaProducerMath.createImage(capText.split("@")[0]);
        } else {
            code = captchaProducer.createText();
            image = captchaProducer.createImage(code);
        }


        // 存储验证码到Redis（示例使用若依框架的缓存常量）
        redisService.setCacheObject(verifyKey, code,  Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        redisTemplate.opsForValue().set("code:", code,  Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);


        // 输出图片流
        response.setContentType("image/jpeg");
        response.setHeader("Cache-Control",  "no-store");
        ImageIO.write(image,  "jpg", response.getOutputStream());
//        // 保存验证码信息
//        String uuid = IdUtils.simpleUUID();
//        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
//
//        String capStr = null, code = null;
//        BufferedImage image = null;
//
//        String captchaType = captchaProperties.getType();
//        // 生成验证码
//        if ("math".equals(captchaType))
//        {
//            String capText = captchaProducerMath.createText();
//            capStr = capText.substring(0, capText.lastIndexOf("@"));
//            code = capText.substring(capText.lastIndexOf("@") + 1);
//            image = captchaProducerMath.createImage(capStr);
//        }
//        else if ("char".equals(captchaType))
//        {
//            capStr = code = captchaProducer.createText();
//            image = captchaProducer.createImage(capStr);
//        }
//
//        redisService.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
//        // 转换流信息写出
//        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
//        try
//        {
//            ImageIO.write(image, "jpg", os);
//        }
//        catch (IOException e)
//        {
//            e.getMessage();
//        }
    }

    /**
     * 登录
     * @param LoginUserDTO
     * @return
     */
    @PostMapping("/login")
    public Object login(@Validated @RequestBody LoginUserDTO LoginUserDTO){
        return userService.login(LoginUserDTO);
    }

    /**
     * 搜索用户--人员列表
     * @param pageIndex
     * @param pageSize
     * @param userName
     * @param roleId
     * @param isRepair
     * @return
     */
    @GetMapping("/search")
    public PageResult<UserVO> searchUsers(
            @RequestParam(required = false) Integer pageIndex,
            @RequestParam(required = false) Integer pageSize,
            @RequestParam(required = false) String userName,
            @RequestParam(required = false) Integer roleId,
            @RequestParam(required = false) Boolean isRepair) {

        return userService.searchUsers(pageIndex, pageSize, userName, roleId, isRepair);
    }
}
